<?php


namespace app\index\controller;

use app\admin\service\RbacService;
use app\common\controller\CommonController;
use app\common\enum\MainEnum;
use app\common\exception\ParameterFailedException;
use app\common\exception\NotFoundException;
use app\common\middleware\AuthToken;
use app\common\model\AddressModel;
use app\common\model\CouponModel;
use app\common\model\UserCouponModel;
use app\common\model\UserCouponRecordModel;
use app\common\service\Lang;
use app\common\validate\CouponValidate;
use app\common\validate\OrderValidate;
use app\Request;
use think\facade\Db;

class CouponController extends CommonController
{
    protected $middleware = [
        AuthToken::class => ['except' => ['getCouponIssueList']],
    ];

    public function getCouponIssueList(Request $request)
    {
        //
        $models = (new CouponModel())->getCouponIssueList();
        return retJson(Lang::GETDone, $models->toArray());
    }

    public function getUserCouponList(Request $request)
    {
        Db::startTrans();
        try {

            $models = (new UserCouponModel())->getUserCouponList($request->userModel->getData('id'));
            Db::commit();
            return retJson(Lang::GETDone, $models->toArray());
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }

    public function postCouponIssue(Request $request)
    {
        Db::startTrans();
        try {

            $params = self::getParam([
                'coupon_id',
            ]);
            (new CouponValidate())->goCheck(__FUNCTION__, $params);

            $model = (new CouponModel())->where('id', $params['coupon_id'])
                ->find();
            if (!$model) {
                throw new NotFoundException();
            }
            if ($model->getData('issue_status') !== MainEnum::COUPON_ISSUE_STATUS['已开启']) {
                throw new ParameterFailedException(['msg' => '该优惠券暂无开启领取渠道']);
            }

            if (strtotime($model->getData('issue_start_time')) > NOW_TIME) {
                throw new ParameterFailedException(['msg' => '该优惠券未到开启时间']);
            }
            if (strtotime($model->getData('issue_end_time')) < NOW_TIME) {
                throw new ParameterFailedException(['msg' => '该优惠券已过期']);
            }
            if ($model->getData('issue_total_count') === 0) {
                //不限制
            }
            else {
                if ($model->getData('issue_total_count') - $model->getData('issue_received_count') <= 0) {
                    throw new ParameterFailedException(['msg' => '该优惠券已被抢完啦~']);
                }
            }

            $userCouponModelsCount = (new UserCouponModel())->where('user_id', $request->userModel->getData('id'))
                ->where('coupon_id', $model->getData('id'))
                ->count();
            if ($userCouponModelsCount >= $model->getData('issue_single_limit')) {
                throw new ParameterFailedException(['msg' => '已达到最大领取数量']);
            }

            #userCoupon
            $prepareUserCouponData = [
                'user_id'    => $request->userModel->getData('id'),
                'coupon_id'  => $model->getData('id'),
                'status'     => MainEnum::COUPON_USER_STATUS['待使用'],
                'start_time' => NOW_TIME,
                'end_time'   => NOW_TIME + $model->getData('valid_time'),
            ];

            #userCouponRecord
            $prepareUserCouponRecordData = [
                'user_id'   => $request->userModel->getData('id'),
                'coupon_id' => $model->getData('id'),
                'get_type'  => MainEnum::COUPON_USER_GET_TYPE['管理员赠送'],
            ];

            (new UserCouponModel())->save($prepareUserCouponData);
            (new UserCouponRecordModel())->save($prepareUserCouponRecordData);

            #领取的数量++
            $model->issue_received_count++;
            $model->save();

            Db::commit();
            return retJson(Lang::Done);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            throw $e;
        }
    }
}